import { ListRawState } from "@/types";
import { createStore } from "vuex";

export interface RootState {
  cartList: CartRawState[];
}

export interface CartRawState extends ListRawState {
  count: number;
  state: boolean;
}

const store = createStore<RootState>({
  state: {
    cartList: JSON.parse(localStorage.getItem("cartList") || "[]"),
  },
  getters: {
    totalPrice(state) {
      return state.cartList
        .filter((v) => v.state)
        .reduce((p, n) => p + n.count * n.price, 0);
    },
    totalState(state) {
      return state.cartList.every(v => v.state)
    }
  },
  mutations: {
    addCart(state, payload: CartRawState) {
      const item = state.cartList.find((v) => v.id === payload.id);
      if (item) item.count++;
      else state.cartList.push(payload);
    },
    subCart(state, payload: CartRawState) {
      const item = state.cartList.find((v) => v.id === payload.id);
      if (item) item.count--;
    },
    switchState(state, payload: CartRawState) {
      const item = state.cartList.find((v) => v.id === payload.id);

      if (item) {

        item.state = !item.state;

      }
    
    },
    switchAllState(state, payload: boolean) {
      state.cartList.forEach((v) => (v.state = payload));
    },
  },
  actions: {},
  modules: {},
});

store.subscribe((mutations, state) => {
  localStorage.setItem("cartList", JSON.stringify(state.cartList));
});

export default store;
